﻿/******************************************************
 * SharePointHelper.cs
 * This class is responsible for all the sharepoint based functionalities in the application
 * ******************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;

namespace SharePointExplorer.SharePoint
{
    class SharePointHelper
    {
        #region Declarations

        App CurrentApplication = (App)Application.Current;

        public static string SharePointSiteUrl { get; set; }
        public static string SiteTitle { get; set; }
        public static string Username { get; set; }
        public static string Password { get; set; }
        public static ClientContext SharePointClientContext { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// Authenticates the sharepoint user
        /// </summary>
        /// <param name="SharePointUrl"></param>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <returns>True if authenticated</returns>
        public static bool Authenticate(string SharePointUrl = "", string UserName = "", string Password = "")
        {
            bool authenticated = false;
            try
            {
                var clientContext = new ClientContext(SharePointUrl);
                SharePointHelper.SharePointClientContext = clientContext;
                Web site = SharePointHelper.SharePointClientContext.Web;
                System.Net.NetworkCredential netCred = new System.Net.NetworkCredential();
                User user = site.CurrentUser;
                SharePointHelper.SharePointClientContext.Load(site);

                SharePointHelper.SharePointClientContext.Load(user);

                SharePointHelper.SharePointClientContext.ExecuteQuery();
                SiteTitle = site.Title; 
                authenticated = true;
              
            }
            catch (Exception)
            {
                authenticated = false;
            }
            return authenticated;
        }

        /// <summary>
        /// Get Document Library 
        /// </summary>
        /// <returns>List of documents</returns>
        public static System.Collections.Generic.List<List> GetDocLibCollection()
        {
            try
            {
                var data = SharePointHelper.SharePointClientContext.LoadQuery(SharePointClientContext.Web.Lists.Where(p => p.BaseType == BaseType.DocumentLibrary));
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                return data.ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Get List Collection
        /// </summary>
        /// <returns>List of lists</returns>
        public static System.Collections.Generic.List<List> GetListCollection()
        {
            ListCollection ListCollection = SharePointClientContext.Web.Lists;
            try
            {
                SharePointClientContext.Load(ListCollection);
                SharePointClientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return ListCollection.ToList();
        }

        /// <summary>
        /// Get Site Collection
        /// </summary>
        /// <returns>List of Sites</returns>
        public static System.Collections.Generic.List<Web> GetSiteCollection() 
        {
            var websCollection = SharePointClientContext.Web.Webs;
            try
            {
                SharePointClientContext.Load(websCollection);
                SharePointClientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return websCollection.ToList<Web>();
        }

        /// <summary>
        /// Get Files in List
        /// </summary>
        /// <param name="ListName"></param>
        /// <returns>List of Files</returns>
        public static System.Collections.Generic.List<Microsoft.SharePoint.Client.File> GetListItemCollection(string ListName)
        {
            List<Microsoft.SharePoint.Client.File> fileList = null;
            try
            {
                Web web = SharePointClientContext.Web;
                if (web != null)
                {
                    var query = SharePointClientContext.LoadQuery(web.Lists.Where(p => p.Title == ListName));
                    SharePointClientContext.ExecuteQuery();
                    var files = query.FirstOrDefault().RootFolder.Files;
                    SharePointClientContext.Load(files, file => file.Include(f => f.ListItemAllFields.Id));
                    SharePointClientContext.Load(files);
                    SharePointClientContext.ExecuteQuery();
                    fileList = files.ToList();
                }
            }
            catch (Exception ex)
            {
            }
            return fileList;
        }

        /// <summary>
        /// Get selected File
        /// </summary>
        /// <param name="Button">Selected Button</param>
        public static void GetFile(object Button)
        {
            try
            {
                Button button = Button as Button;
                Microsoft.SharePoint.Client.File buttonData = (button).DataContext as Microsoft.SharePoint.Client.File;
                SharePointHelper.SharePointSiteUrl = buttonData.ServerRelativeUrl;
                SharePointUtils.FileName = string.Concat(SharePointClientContext.Url, buttonData.ServerRelativeUrl);
                SharePointUtils.FileId = buttonData.ListItemAllFields.Id;
            }
            catch (Exception ex)
            { }

        }

        /// <summary>
        /// Move selected File
        /// </summary>
        /// <param name="ToList">Target List</param>
        public static void MoveFile(string ToList)
        {
            try
            {
                var file = SharePointHelper.SharePointClientContext.Web.Lists.GetByTitle(SharePointUtils.FromList).GetItemById(SharePointUtils.FileId).File;
                var list = SharePointHelper.SharePointClientContext.Web.Lists.GetByTitle(ToList);
                SharePointHelper.SharePointClientContext.Load(file);
                SharePointHelper.SharePointClientContext.Load(list);
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                string moveURL = string.Concat(SharePointClientContext.Url + "/", ToList);
                file.MoveTo(moveURL + "/" + file.Name, MoveOperations.Overwrite);
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                SharePointUtils.MoveFlag = false;
                ((App)Application.Current).MainWindowInstance.DeactivateButton.IsEnabled = false;
                ((App)Application.Current).MainWindowInstance.imgDeactivate.Source = new BitmapImage(new Uri("/SharePointExplorer;component/Images/Deactivate_disabled.png", UriKind.Relative));
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// Copy selected File
        /// </summary>
        /// <param name="ToList">Target List</param>
        public static void CopyFile(string ToList)
        {
            try
            {
                var file = SharePointHelper.SharePointClientContext.Web.Lists.GetByTitle(SharePointUtils.FromList).GetItemById(SharePointUtils.FileId).File;
                var list = SharePointHelper.SharePointClientContext.Web.Lists.GetByTitle(ToList);
                SharePointHelper.SharePointClientContext.Load(file);
                SharePointHelper.SharePointClientContext.Load(list);
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                file.CopyTo(ToList + "/" + file.Name, true);
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                SharePointUtils.CopyFlag = false;
                ((App)Application.Current).MainWindowInstance.DeactivateButton.IsEnabled = false;
                ((App)Application.Current).MainWindowInstance.imgDeactivate.Source = new BitmapImage(new Uri("/SharePointExplorer;component/Images/Deactivate_disabled.png", UriKind.Relative));
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// Delete selected File
        /// </summary>
        public static void Delete()
        {
            try
            {
                var file = SharePointHelper.SharePointClientContext.Web.Lists.GetByTitle(SharePointUtils.FromList).GetItemById(SharePointUtils.FileId).File;
                var list = SharePointHelper.SharePointClientContext.Web.Lists.GetByTitle(SharePointUtils.FromList);
                SharePointHelper.SharePointClientContext.Load(file);
                SharePointHelper.SharePointClientContext.Load(list);
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                file.DeleteObject();
                SharePointHelper.SharePointClientContext.ExecuteQuery();
                SharePointUtils.DeleteFlag = false;
                ((App)Application.Current).MainWindowInstance.DeactivateButton.IsEnabled = false;
                ((App)Application.Current).MainWindowInstance.imgDeactivate.Source = new BitmapImage(new Uri("/SharePointExplorer;component/Images/Deactivate_disabled.png", UriKind.Relative));
            }
            catch (Exception ex)
            { }
            //SharePointExplorer.Classes.KinectHelper.TogglePostureDetectedHandler(false);
        }

        /// <summary>
        /// Reads a particular file out loud
        /// </summary>
        /// <param name="FileName">File to read</param>
        /// <returns>Contents of file to read</returns>
        public static string ReadFile(string FileName)
        {
            string content = string.Empty;
            try
            {
                var page = Microsoft.SharePoint.Client.File.OpenBinaryDirect(SharePointClientContext, FileName);
                StreamReader reader = new StreamReader(page.Stream);
                content = reader.ReadToEnd();
                content = Regex.Replace(content, @"[\r\n\t ]+", " ");
            }
            catch (Exception ex)
            { }
            return content;
        }

        #endregion
    }


}
